package com.ccteam.shared.domain.playlistsheet.music

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.shared.api.SearchDataSource
import com.ccteam.shared.data.search.HomeSearchMusicPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.playlistsheet.AddMediaItem
import com.ccteam.shared.utils.EMPTY_STRING
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/17
 *
 */
class PlaylistSheetAddedMusicDataUseCase @Inject constructor(
    private val searchDataSource: SearchDataSource,
): PagingUseCase<String?, AddMediaItem>(
    Dispatchers.IO
) {

    override fun execute(parameters: String?): Flow<PagingData<AddMediaItem>> {
        if(parameters.isNullOrEmpty()){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            HomeSearchMusicPagingSource(parameters,searchDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                AddMediaItem(it.id,it.name,it.artists,it.imgUrl ?: EMPTY_STRING,false)
            }
        }
    }
}